﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Web;
using UtilZ.Dotnet.Ex.Json;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.Ex.Model;
using UtilZ.Dotnet.WindowsDesktopEx.NativeMethod;

namespace UtilZ.Tool.HostQuery
{
    [Route("api/v1/os")]
    internal class QueryCore : IDisposable
    {
        private readonly IOSQuery _query;
        private readonly HttpServer _httpServer;

        public QueryCore()
        {
            if (EnvironmentEx.IsWindowPlatform())
            {
#pragma warning disable CA1416
                this._query = new WindowsQuery();
#pragma warning restore CA1416
            }
            else
            {
#pragma warning disable CA1416
                this._query = new LinuxQuery();
#pragma warning restore CA1416
            }

            string httpPortStr = System.Configuration.ConfigurationManager.AppSettings["httpPort"];
            int httpPort;
            if (!int.TryParse(httpPortStr, out httpPort))
            {
                httpPort = 5300;
            }

            //http服务器
            var handler = new HttpRequestHandler();
            var apiMiddleware = new ApiMiddleware();
            apiMiddleware.AddApi(this);
            handler.AddMiddleware(apiMiddleware, 1);

            var httpConfig = new HttpServerConfig()
            {
                ListenEndPoint = new IPEndPoint(IPAddress.Any, httpPort)
            };
            this._httpServer = new HttpServer(httpConfig, handler);
        }


        internal void Start()
        {
            this._httpServer.Start();
        }

        /// <summary>
        /// 根据进程ID查询进程参数
        /// http://127.0.0.1:5300/api/v1/os/queryProArgs?pid=123
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpGet("queryProArgs?pid={pid}")]
        public ApiResult QueryProArgs(int pid)
        {
            try
            {
                string args = this._query.QueryProcessStartArgs(pid);
                return new ApiResult(ApiResultStatus.Succes, args);
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
                return new ApiResult(ApiResultStatus.Exception, ex.ToString());
            }
        }


        /// <summary>
        /// 获取崩溃进程ID列表
        /// http://127.0.0.1:5300/api/v1/os/getCrushProcessIdList
        /// </summary>
        /// <returns></returns>
        [HttpGet("getCrushProcessIdList")]
        public ApiResult GetCrushProcessIdList()
        {
            try
            {
                var crushProcessIdList = this._query.GetCrushProcessIdList();
                return new ApiResult(ApiResultStatus.Succes, JsonSerializer.SerializeObject(crushProcessIdList));
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
                return new ApiResult(ApiResultStatus.Exception, ex.ToString());
            }
        }

        /// <summary>
        /// 判断句柄指示的进程是否未响应
        /// http://127.0.0.1:5300/api/v1/os/isNoResponse?handler=123
        /// </summary>
        /// <returns></returns>
        [HttpGet("isNoResponse?handler={handler}")]
        public ApiResult IsNoResponse(long handler)
        {
            try
            {
                var mainWindowHandle = new IntPtr(handler);
                var isNoResponse = this._query.IsNoResponse(mainWindowHandle);
                return new ApiResult(ApiResultStatus.Succes, isNoResponse.ToString());
            }
            catch (Exception ex)
            {Loger.Error(ex);
                return new ApiResult(ApiResultStatus.Exception, ex.ToString());
            }
        }


        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            this._httpServer.Dispose();
        }
    }
}
